/**
 * [42] 接雨水
 *
 * @format
 * @lc app=leetcode.cn id=42 lang=javascript
 */

// @lc code=start
/**
 * @param {number[]} height
 * @return {number}
 */
var trap = function (height) {
    const WALL = height.reduce((a, b) => a + b)
    const MAX = height.reduce((a, b) => (a > b ? a : b))
    const TOTAL = MAX * height.length
    // let [max, wall] = [0, 0]
    // for (let i = 0; i < height.length; i++) {
    //     if (height[i] > max) max = height[i]
    //     wall += height[i]
    // }
    // const TOTAL = max * height.length
    let [air, highest] = [0, 0]
    for (let i = 0; height[i] < MAX; i++) {
        if (height[i] > highest) highest = height[i]
        air += MAX - highest
    }
    highest = 0
    for (let i = height.length - 1; height[i] < MAX; i--) {
        if (height[i] > highest) highest = height[i]
        air += MAX - highest
    }
    return TOTAL - WALL - air
}
// var trap = function (height) {
//     const max = height.reduce((a, b) => (a > b ? a : b))
//     let sum = 0
//     for (let i = 1; i <= max; i++) {
//         let temp = -1
//         for (let j = 0; j < height.length; j++) {
//             if (i > height[j]) temp == -1 ? null : temp++
//             else temp == -1 ? (temp = 0) : (sum += temp), (temp = 0)
//         }
//     }
//     return sum
// }
// var trap = function (height) {
//     let water = 0
//     const pond = []
//     for (let i = 0; i < height.length; i++) {
//         for (let j = pond.length; j < height[i]; j++) pond.push(0)
//         for (let j = 0; j < pond.length; j++) {
//             if (j + 1 > height[i]) pond[j]++
//             else (water += pond[j]), (pond[j] = 0)
//         }
//     }
//     return water
// }
// debugger
// const height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
// console.log(trap(height))
// @lc code=end
